#define _GNU_SOURCE
#include "pthread.h"
#include "stdio.h"
#include "unistd.h"
#include "mqueue.h"
static mqd_t mq_handler;
void *thread_func1(void *arg)
{
     printf("thread_func1准备向队列写数据... \n");

    sleep(1);

    char *msg = "hello atguigu";
    mq_send(mq_handler, msg, 14, 1);
    return NULL;
}
void *thread_func2(void *arg)
{
    printf("thread_func2准备从队列读数据.. \n");
    char buff[100];

    // 以阻塞的方式等待数据
    ssize_t len = mq_receive(mq_handler, buff, 100, NULL);
    printf("读取到数据 buff=%s,len =%ld \n", buff, len);
    return NULL;
}

int main(int argc, char const *argv[])
{
    char *mq_name = "/test_mq";

    // 创建消息队列 6:420
    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = 100;
    mq_handler = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    if (mq_handler == (mqd_t)-1)
    {
        printf("队列创建失败!");
        return -1;
    }

    pthread_t pt1;
    pthread_t pt2;
    pthread_create(&pt1, NULL, thread_func1, NULL);
    pthread_create(&pt2, NULL, thread_func2, NULL);

    // 加一个休眠,让分线程有机会执行
    pthread_join(pt1, NULL);
    pthread_join(pt2, NULL);

    // 销毁队列
    mq_unlink(mq_name);

    return 0;
}
